package com.lin.service.Impl;

import com.lin.entity.User;
import com.lin.mapper.UserMapper;
import com.lin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private UserMapper accountMapper;

    @Autowired
    public void setAccountMapper(UserMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    @Override
    public boolean add(User user) {
        return accountMapper.add(user);
    }

    @Override
    public boolean delete(Integer uid) {
        return accountMapper.delete(uid);
    }

    @Override
    public boolean update(User user) {
        return accountMapper.update(user);
    }

    @Override
    public User queryById(Integer uid) {
        return accountMapper.queryById(uid);
    }

    @Override
    public List<User> queryAll() {
        return accountMapper.queryAll();
    }

    @Override
    @Transactional
    public boolean transfer(String from, String to, Integer money) {
        boolean tfo = false;
        boolean tfi = false;
        try {
            tfo = accountMapper.transferOut(from, to, money);
            // int i = 1/0; // 模拟业务错误
            tfi = accountMapper.transferIn(to, from, money);
        } catch (Exception e) {
            System.out.println("转账失败, 请重试!\n" + e);
        }
        return tfo == tfi && tfo; // 如果两个都成功, 则返回true, 否则返回false
    }
}
